/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-07-14 09:34:03
 * @LastEditTime : 2023-07-18 09:44:39
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Pages\Front\Assets\Modal\TableList.jsx
 * @Description  :
 */
import request from 'umi-request'
import { useEffect, useRef, useState } from 'react'
import { ProTable } from '@ant-design/pro-components'
import { useEventEmitter, useSize } from 'ahooks'
import { message } from 'antd'
import { ModalBox } from '../../../../Common/Modal/ModalBox'
import { FrontModalBox } from '.'

import { ProjectListTem } from '../../Template'

const ModalBoxList = [
    'Annex',
    'AnnexMore',
    'LabStressMachine',
    'LabUniversalRebar',
    'LabReboundHammer',
    'LabCoverProtector',
    'OpenExcel',
    'MonitoringModal',
    'FileManagement',
]

const FrontBoxList = [
    'APIAnnexModal',
    'InspectionDetails',
    'RiskDetailsBox',
    'SecurityActivityDetailBox',
    'AiDetailsModal',
    'TableList',
    'PersonDetailsModal',
]

const additionalTemp = {
    ProjectListTem,
}

export const TableList = ({ data }) => {
    const [messageApi, contextHolder] = message.useMessage()
    const { type, uuid, OrganizationUuid } = data
    const headers = { Authorization: sessionStorage.getItem('TOKEN') }

    const tableBox = useRef(null)
    const BoxSize = useSize(tableBox)
    const actionRef = useRef()
    const formRef = useRef()
    const OptionsEvent = useEventEmitter()
    const [configure, setConfigure] = useState()
    const [IndexNumber, setIndexNumber] = useState(1)
    const [SizeNumber, setSizeNumber] = useState(10)
    const [OptionsCall, setOptionsCall] = useState()
    const [FrontOptionsCall, setFrontOptionsCall] = useState()

    const [Params, setParams] = useState()

    useEffect(() => {
        const getList = async () => {
            const ClientData = JSON.parse(localStorage.getItem('ClientData'))
            const page = await import(`./List`).catch(() => false)
            const data = await page[type]({ uuid, OptionsEvent, OrganizationUuid, ClientData })
            setSizeNumber(data.pageSize)
            setConfigure(data)
            setParams(data.params)
        }
        if (type) getList()
    }, [type, uuid, OptionsEvent, OrganizationUuid])

    OptionsEvent.useSubscription(val => {
        const { type, state, tips } = val
        if (FrontBoxList.includes(type)) setFrontOptionsCall(val)
        else {
            if (type === 'tips') messageApi[state](tips)
            if (ModalBoxList.includes(type)) setOptionsCall(val)
        }
    })

    const ActiveEvent = useEventEmitter()
    ActiveEvent.useSubscription(val => {
        setParams(e => ({ ...e, organizationUuid: val }))
    })

    return (
        <div className="FrontTableList" ref={tableBox}>
            {contextHolder}
            {configure?.leftMenu &&
                additionalTemp[configure.leftMenu] &&
                (() => {
                    const Template = additionalTemp[configure.leftMenu]
                    return <Template ActiveEvent={ActiveEvent} count />
                })()}
            {configure && BoxSize && (
                <ProTable
                    actionRef={actionRef}
                    formRef={formRef}
                    rowKey="uuid"
                    columns={configure.columns}
                    cardBordered
                    params={Params}
                    request={async (params = {}) => {
                        delete params.current
                        params.pageIndex = IndexNumber ?? 1
                        if (params.IsCheckbox) {
                            let data = {}
                            params.IsCheckbox.forEach(item => (data = { ...data, [item]: true }))
                            delete params.IsCheckbox
                            params = { ...params, ...data }
                        }
                        if (params.SearchSort) {
                            const { SearchSort } = params
                            SearchSort.forEach((item, index) => {
                                const [field, sort] = item.split('-')
                                params[field] = `${sort}@${index}`
                            })
                            delete params.SearchSort
                        }
                        return request(configure.get, { params, headers }).then(data => {
                            if (data.list) return { data: data.list, total: data.total, success: true }
                            else return { data, success: true }
                        })
                    }}
                    search={
                        configure.hideInSearch
                            ? false
                            : {
                                  optionRender: (searchConfig, formProps, dom) => {
                                      return [...dom.reverse()]
                                  },
                              }
                    }
                    pagination={{
                        pageSize: SizeNumber,
                        showSizeChanger: true,
                        onChange: (e, a) => {
                            setIndexNumber(e)
                            setSizeNumber(a)
                        },
                    }}
                    scroll={(() => {
                        let { width, height } = BoxSize
                        const { hideInSearch, leftMenu } = configure
                        let x = leftMenu ? width - 400 : width
                        let y = hideInSearch === undefined ? height - 265 : height - 170
                        return { x, y }
                    })()}
                />
            )}

            <FrontModalBox OptionsCall={FrontOptionsCall} />
            <ModalBox OptionsCall={OptionsCall} />
        </div>
    )
}
